// pages/residenceCertification/residenceCertification.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
import { jump, removeStorage, setStorage, getStorage } from "../../utils/utils";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //展示推荐列表
    showList:true,
    // 用户信息
    userInfo: null,
    // 用户真实姓名
    realName: null,
    // 是否是目标小区
    target: null,
    // 同名房间信息
    sameHouseData: null,
    // 选中小区数据
    communitySelect: null,
    // 选中小区编号
    communityCode: null,
    // 小区选中项
    communityIndex: null,

    // 楼栋列表
    buildingList: null,
    // 楼栋是否展开
    buildingExpend: false,
    // 楼栋选中项
    buildingIndex: 0,
    // 自定义楼栋
    buildingText: '',

    // 单元列表
    unitList: null,
    // 单元是否展开
    unitExpend: false,
    // 单元选中项
    unitIndex: 0,
    // 自定义单元
    unitText: '',

    // 房间号列表
    houseNoList: null,
    // 房间号是否展开
    houseNoExpend: false,
    // 房间号选中项
    houseNoIndex: -1,// 0,
    // 自定义房间号
    houseNoText: '',
    timeout: 3000,// 请求接口超时时间
  },
  
  // 是否重载
  reload: true,
  // 请求loading
  loading: false,

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.nameModify) {
      this.nameModify = false
      return
    }
    const { userInfo, communityCode } = this.data
    if (this.reload) {
      this.getInfo()
    } else {
      this.setData({
        communityIndex: userInfo.list?.findIndex(item => item.communityCode === communityCode)
      })
    }
    this.reload = true

    this.getSwitch()
  },
  // 获取推荐居住地小区展示开关
  getSwitch: async function(){
    const res = await request.get('getSwitchData',{
      switchType:1
    })
    if(res.httpStatus===200){
      this.setData({
        showList:res.data[0].miniAppSwitch===1
      })
    }
  },
  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		this.modal = this.selectComponent('#modal')
	},
  // 获取居住地认证信息
  async getInfo(){
    let that = this
    let { timeout } = that.data
    const res = await request.get(api.verifyInfo,{},{ timeout:timeout })
    // 请求报错
    if(res.errMsg && res.errMsg.indexOf("请求超时") !== -1){
      wx.showModal({
        content: '当前网络环境不好',
        cancelText: '关闭',
        confirmText: "重新加载",
        success(res) {
          if (res.confirm) {
            that.setData({
              timeout: 5000
            }, () => {
              that.getInfo()
            })
          }
        }
      })
      return
    }
    const userInfo = res?.data || {}
    if (userInfo.building) {
      userInfo.building = userInfo.building.replace('号楼', '')
    }
    if (userInfo.unit) {
      userInfo.unit = userInfo.unit.replace('单元', '')
    }
    console.log('居住地认证信息：', userInfo)

    const { list, icon, fromNickName, nickName, peopleNumber, phone, phones, userCommunityBindInfoId, ...communitySelect } = userInfo

    this.setData({
      userInfo,
      realName: userInfo.realName,
      communitySelect,
      communityCode: userInfo.communityCode,
      communityIndex: userInfo.list?.findIndex(item => item.communityCode === userInfo.communityCode),
      timeout: 3000
    })

    this.loading = true
    if (userInfo.communityCode) {
      this.getBuildInfo(userInfo.communityCode, !!userInfo.buildingDetail)
    } else {
      this.getSameHouseInfo(userInfo)
    }
  },
  // 获取同名房间信息
  async getSameHouseInfo(data) {
    const { communityCode: code, buildingList, buildingIndex, buildingText, unitList, unitIndex, unitText, houseNoList, houseNoIndex, houseNoText  } = this.data
    const { communityCode, building, unit, houseNo } = data || {
      communityCode: code,
      building: buildingText || buildingList[buildingIndex]?.buildingName,
      unit: unitText || unitList[unitIndex]?.unitName,
      houseNo: houseNoText || houseNoList[houseNoIndex]?.houseName,
    }
    if (!communityCode || !building || !unit || !houseNo) {
      this.loading = false
      this.setData({
        sameHouseData: {}
      })
      return
    }
    let that = this
    let { timeout } = that.data

    const res = await request.get(api.sameHouse, {
      communityCode,
      building,
      unit,
      houseNo,
    },{ timeout: timeout })
    console.log('同名房间信息：', res?.data)
    // 请求报错
    if(res.errMsg && res.errMsg.indexOf("请求超时") !== -1){
      this.loading = false
      wx.showModal({
        content: '当前网络环境不好',
        cancelText: '关闭',
        confirmText: "重新加载",
        success(res) {
          if (res.confirm) {
            that.setData({
              timeout: 5000
            }, () => {
              that.getSameHouseInfo(data)
            })
          }
        }
      })
      return
    }

    this.setData({
      sameHouseData: res?.data || {},
      timeout: 3000
    })
    this.loading = false
  },
  // 根据小区编号获取楼层信息
  async getBuildInfo(communityCode, isInit) {
    
    const { userInfo, communitySelect } = this.data
    let that = this
    const { timeout } = that.data
    if (!communityCode) {
      this.loading = false
      wx.showToast({
        icon: 'none',
        title: '该小区无编号，无法查询楼层信息',
      })
      return
    }
    let res
    if (communitySelect?.target === 1) {
      res = await request.get(api.buildingInfoList, { communityCode },{ timeout })
      // 请求报错
      if(res.errMsg && res.errMsg.indexOf("请求超时") !== -1){
        wx.showModal({
          content: '当前网络环境不好',
          cancelText: '关闭',
          confirmText: "重新加载",
          success(res) {
            if (res.confirm) {
              that.setData({
                timeout: 5000
              }, () => {
                that.getBuildInfo(communityCode, isInit)
              })
            }
          }
        })
        return
      }
    }
    if (!res?.data?.length) {
      res = {
        data: Array.from({ length: 50 }).map((_, bIndex) => ({
          buildingName: `${bIndex + 1}`,
          unitList: Array.from({ length: 20 }).map((_, uIndex) => ({
            unitName: `${uIndex + 1}`,
            houseList: []
          }))
        }))
      }
    }
    const buildingList = res?.data
    let buildingIndex = 0
    if (isInit) {
      buildingIndex = buildingList.findIndex(item => item.buildingName === userInfo.building)
    }
    const unitList = buildingList[buildingIndex === -1 ? 0 : buildingIndex]?.unitList
    let unitIndex = 0
    if (isInit) {
      unitIndex = unitList.findIndex(item => item.unitName === userInfo.unit)
    }
    const houseNoList = unitList[unitIndex === -1 ? 0 : unitIndex]?.houseList
      .map(houseName => ({ houseName }))
    let houseNoIndex = -1 // 0
    if (isInit) {
      houseNoIndex = houseNoList.findIndex(item => item.houseName === userInfo.houseNo)
    }

    console.log('当前选中小区楼层信息：', buildingList)

    this.setData({
      buildingList,
      unitList,
      houseNoList,
      buildingIndex,
      unitIndex,
      houseNoIndex,
      ...(isInit ? {
        ...(buildingIndex === -1 ? { buildingText: userInfo?.building || '' } : {}),
        ...(unitIndex === -1 ? { unitText: userInfo?.unit || '' } : {}),
        ...(houseNoIndex === -1 ? { houseNoText: userInfo?.houseNo || '' } : {}),
      } : {}),
      buildingExpend: buildingIndex > 4 || buildingIndex === -1,
      unitExpend: unitIndex > 4 || unitIndex === -1,
      houseNoExpend: houseNoIndex > 4 || unitIndex === -1,
    })

    this.getSameHouseInfo()
  },
  // 地址选中变化
  selectChange(e) {
    if (this.loading) return
    this.loading = true
    let { userInfo, communityCode, buildingList, buildingIndex, unitList, unitIndex, houseNoIndex, houseNoList } = this.data
    const dataset = e?.currentTarget.dataset || {}

    switch (dataset.type) {
      // 居住地小区变化时，获取小区楼层信息
      case 'communityIndex':
        if (userInfo?.list) {
          const communitySelect = userInfo.list[dataset.index]
          const newCommunityCode = communitySelect?.communityCode
          if (communityCode === newCommunityCode) {
            this.loading = false
            return
          }
          this.setData({
            communityIndex: dataset.index,
            communityCode: newCommunityCode,
            communitySelect,
            buildingText: '',
            unitText: '',
            houseNoText: '',
          })
          this.getBuildInfo(newCommunityCode)
          return
        }
        break;
      // 楼栋
      case 'buildingIndex':
        if (dataset.index === buildingIndex) {
          this.loading = false
          return
        }
        unitList = buildingList[dataset.index]?.unitList
        houseNoList = unitList[0]?.houseList.map(houseName => ({ houseName }))
        console.log('当前楼栋单元信息：', unitList)
        this.setData({
          buildingIndex: dataset.index,
          buildingText: '',
          unitList,
          unitIndex: 0,
          unitText: '',
          houseNoList,
          houseNoIndex: -1,// 0,
          houseNoText: '',
          unitExpend: false,
          houseNoExpend: false,
        })
        break;
      // 单元
      case 'unitIndex':
        if (dataset.index === unitIndex) {
          this.loading = false
          return
        }
        houseNoList = unitList[dataset.index]?.houseList.map(houseName => ({ houseName }))
        console.log('当前单元楼层信息：', unitList)
        this.setData({
          unitIndex: dataset.index,
          unitText: '',
          houseNoList,
          houseNoIndex: -1,// 0,
          houseNoText: '',
          houseNoExpend: false,
        })
        break;
      // 房间号
      case 'houseNoIndex':
        if (dataset.index === houseNoIndex) {
          this.loading = false
          return
        }
        console.log('当前房间号：', houseNoList[dataset.index]?.houseName)
        this.setData({
          houseNoIndex: dataset.index,
          houseNoText: '',
        })
        break;
    
      default:
        break;
    }

    this.getSameHouseInfo()
  },
  // 展开/收起变化
  extendChange(e) {
    const type = e?.currentTarget.dataset.type

    if (type) {
      this.setData({
        [type]: !this.data[type]
      })
    }
  },
  // 自定义地址变化
  textChange(e) {
    const type = e?.currentTarget.dataset.type
    const textValue = (e?.detail.value || '').replace(/[^\a-zA-Z\u4E00-\u9FA5\d#-]/g,'')
    console.log(type, textValue);

    switch (type) {
      // 楼栋
      case 'buildingText':
        this.setData({
          buildingIndex: null,
          buildingText: textValue
        })
        break;
      // 单元
      case 'unitText':
        this.setData({
          unitIndex: null,
          unitText: textValue
        })
        break;
      // 房间号
      case 'houseNoText':
        this.setData({
          houseNoIndex: null,
          houseNoText: textValue
        })
        break;
    
      default:
        this.setData({
          [type]: textValue
        })
        break;
    }

    this.getSameHouseInfo()
  },
  // 文本框聚焦
  inputFocus() {
    this.setData({
      autoFocus: true
    })
  },
  // 跳转名称修改
  nameHandle(){
    this.nameModify = true
    jump('residenceCertificationNameSet', {
      title: encodeURIComponent(this.data.realName || ''),
      auth: true
    })
 },
  // 立即提交
  async submit(e) {
    const pass = e.currentTarget.dataset.pass
    const { communitySelect, realName, communityCode, buildingList, buildingIndex, buildingText, unitList, unitIndex, unitText, houseNoList, houseNoIndex, houseNoText } = this.data
    if (!realName) {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none'
      })
      return
    }
    if (!realName.trim()) {
      wx.showToast({
        title: '姓名不能全是空格',
        icon: 'none'
      })
      return
    }
    if (!communityCode) {
      wx.showToast({
        title: communitySelect.communityName ? '该小区无编号，无法添加' : '请选择居住地小区',
        icon: 'none'
      })
      return
    }
    const buildingInfo = buildingList[buildingIndex]
    if (!buildingText && !buildingInfo) {
      wx.showToast({
        title: '请选择楼栋',
        icon: 'none'
      })
      return
    }
    const unitInfo = unitList[unitIndex]
    if (!unitText && !unitInfo) {
      wx.showToast({
        title: '请选择单元',
        icon: 'none'
      })
      return
    }

    const houseNoInfo = houseNoList[houseNoIndex]
    if (!houseNoText && !houseNoInfo) {
      wx.showToast({
        title: houseNoList.length ? '请选择房间号' : '请输入房间号',
        icon: 'none'
      })
      return
    }

    if (this.loading) return
    this.loading = true
    if (!pass) {
      await this.getSameHouseInfo()
      if (this.data.sameHouseData.peopleNumber >= 3) {
        this.modal.show()
        this.loading = false
        return
      }
    }
    const { id, type, createBy, createTime, deleted, ...communityInfo } = communitySelect
    const params = {
      ...communityInfo,
      realName,
      building: buildingText || buildingInfo.buildingName,
      unit: unitText || unitInfo.unitName,
      houseNo: houseNoText || houseNoInfo.houseName,
    }
    console.log('居住地认证提交参数：', params)

    const res = await request.post(api.commitInfo, params)

    console.log('居住地认证提交返回：', res)
    if (res?.httpStatus === 200) {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      })
      
      //切换居住地后仅修改----start------------------------
      this.clearStorage()
      //切换居住地后仅修改----end--------------------------

      // const {pageTurnType} = res.data
      // if(pageTurnType===1){
        wx.switchTab({
          url: '/pages/index/index',
        })
      // }else{
      //   wx.redirectTo({
      //     url: '/pages/coinCertificate/coinCertificate',
      //   })
      // }
    }
    this.modal.hide()
    this.loading = false
  },

  // ------------------start----------------------------------
  // 仅修改----切换居住地后清除缓存
  async clearStorage(){
    removeStorage("userType")
    removeStorage("latitude")
    removeStorage("longitude")
    removeStorage("addressInfo")
    removeStorage("communityBind")
    removeStorage("communityName")
    removeStorage("communityCode")
    removeStorage("userIdentity")
    //重新缓存“用户类型”
    const response = await request.get(api.userType, null, { loading: false })
    // 用户类型 1普通用户 2目标用户
    setStorage("userType", response?.data ? 2 : 1)
    // 获取用户信息
    this.updateInfo()
  },
  // 仅修改----重新缓存用户信息
	async updateInfo() {
		const userId = getStorage("userId");
		if (userId) {
      const res = await request.get(
				api.homeDetail, {
					userId
				}, {
					loading: false,
					modal: false
				}
			);
			setStorage("communityBind", res?.data.communityBind || false);
			setStorage("communityName", res?.data.communityName || " ");
      setStorage("communityCode", res?.data.communityId || " ");
      setStorage("userIdentity", res.data?.userIdentity || " ");
		}
  },
  //----------------end-------------------------------------


  // 跳转小区搜索
  jumpCommunity(){
    this.reload = false
    jump('chooseCommunity')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    return shareOptions('default', e)
  },
})